# -*- coding: UTF-8 -*-
import csv
import json
import os
import tempfile

import web

urls = (
    '/', 'upload'
)

from aip import AipOcr

""" 你的 APPID AK SK """
APP_ID = '11322449'
API_KEY = 'EVyjdsDGim5jlRAPSf1wVAv5'
SECRET_KEY = 'eYXPid0PvAL9FK7BeCSylGd0lyEVj348'

client = AipOcr(APP_ID, API_KEY, SECRET_KEY)


class upload:
    def GET(self):
        return """<html><head><meta charset="utf-8" /></head><body>
                    <form method="POST" enctype="multipart/form-data">
                    <input type="file" name="myfile" />
                    <br/>
                    <input type="submit" name="提交"/>
                    </form>
                    <p>提交后，耐心等待片刻，即可出结果.</p>
                    </body></html>"""

    def POST(self):
        x = web.input(myfile={})
        data = x['myfile'].file.read()
        if not data:
            return """<html><head><meta charset="utf-8" /></head><body>
                    <p>请选择要上传的文件.</p>
                    </body></html>"""
        filename = x['myfile'].filename
        filename = filename[0:filename.find(".")]

        j = client.tableRecognition(data, {'result_type': 'json', })
        # print(j)
        if j.get("result"):
            items = j["result"]["result_data"]
            # print(items)
            items = json.loads(items, encoding="utf-8")
            items = items["forms"][0]["body"]
            # print(items)

            items = sorted(items, key=lambda r: (r['row'], r['column']))
            # print(items)

            file_path = tempfile.mktemp(prefix=f'recognize_table_{filename}', suffix=".csv")

            with open(f"{file_path}", "w", newline="", encoding="gbk") as datacsv:
                csvwriter = csv.writer(datacsv, dialect=("excel"))
                last_item_row_index = -1
                # csv文件插入一行数据，把下面列表中的每一项放入一个单元格（可以用循环插入多行）
                row_content_arr = []
                for item in items:
                    current_item_row_index = int(item["row"][0])
                    current_item_content = item["word"]
                    if current_item_row_index == last_item_row_index:
                        row_content_arr.append(current_item_content)
                    else:
                        if last_item_row_index >= 0:
                            csvwriter.writerow(row_content_arr)
                        row_content_arr.clear()
                        last_item_row_index += 1
                        row_content_arr.append(current_item_content)
                else:
                    csvwriter.writerow(row_content_arr)

            web.header('Content-Type', "csv")
            web.header('Content-disposition', f'attachment; filename={filename}.csv')
            with open(f"{file_path}", "r", encoding="gbk") as f:
                retun_data = f.read().encode("gbk")
            if not retun_data:
                retun_data = "I'm so sorry , it doesn't work now , please call sam for help ."
            os.remove(file_path)
            return retun_data  # your blob
        else:
            return j


if __name__ == "__main__":
    app = web.application(urls, globals())
    app.run()
